/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pl.cezary.butler.walili.server.shuffling;

import java.util.Random;

/**
 *
 * @author Czarek
 */
public class GapIdGenerator implements IShufflingIdGenerator{
    
    private final int[] counters;
    private final int gap;
    private int offset =0;
    private int similarInRow = 0 ;
    private final int skew;
    

    public GapIdGenerator(int gap) {
        this.gap = gap;
        skew=Math.max(1,Math.abs(gap/3+1));
        counters=new int[gap];
        for(int i=0;i<gap;++i){
            counters[i]=i;
        }
    }
    
    public int getNextId(final int prev, final boolean condition) {
        final int result;
        if(!condition)
            ++offset;
        result=counters[offset%gap]+=gap;        
        return result;
    }
    

    @Override
    public void assureIds(IShufflable shuffable1, IShufflable shuffable2, boolean condition) {        
        if(condition)
            ++similarInRow;
        else
            similarInRow=0;
        if(similarInRow>=gap){
            offset+=+skew;
            similarInRow=0;
        }
        Integer sid1 = shuffable1.getShuffleId();
        Integer sid2 = shuffable2.getShuffleId();
        if (sid1 != null && sid2 != null) {
            return;
        }

        final Integer prev = (sid1 != null ? sid1 : sid2);
        int iPrev =(prev != null) ? prev : ((true)?0:1);
        if (sid1 == null&&shuffable1!=shuffable2) {
            final int genId = getNextId(iPrev, condition);
            iPrev = genId;
            shuffable1.setShuffleId(genId);
        }
        if (sid2 == null) {
            shuffable2.setShuffleId(getNextId(iPrev, condition));
        }
    }

    @Override
    public String toString() {
        return "GapIdGenerator{" + "gap=" + gap + '}';
    }
    
    
    
}
